package com.rc.saas.tenant.controller.operator;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.base.HttpConstant;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.model.operator.TenantOperator;
import com.rc.saas.tenant.model.operator.TenantOperatorExample;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.operator.TenantOperatorService;
import com.rc.saas.tenant.search.operator.OperatorSearch;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.operator.OperatorElecStationVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * 分销商管理
 * Created by sven on 2019/9/18
 */
@Controller
@RequestMapping("/tenantOperator")
public class TenantOperatorController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(TenantOperatorController.class);

    private String prefix = "/templates/operator";

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private TenantOperatorService tenantOperatorService;

    /**
     * 首页
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/operator/tenantOperator";
    }

    /**
     * 列表
     *
     * @param search
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo list(OperatorSearch search) {
        PageInfo<TenantOperator> page = tenantOperatorService.listPageTenantOperator(search);
        WebPageInfo webPageInfo = new WebPageInfo(page.getList(), Long.valueOf(page.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 新增
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        //默认的分销商号码
        //TenantUser user = ShiroUtils.getSessionUser();
        //Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
        //if (tenant != null) {
        //    uidGenerator.genDefaultTenantOperatorCode(tenant.getTenantPrefix());
        //}

        return prefix + "/addTenantOperator";
    }

    /**
     * 修改
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable("id") String id, Model model) {
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(id);
        model.addAttribute("tenantOperator", tenantOperator);
        return prefix + "/editTenantOperator";
    }

    /**
     * 新增保存
     *
     * @param tenantOperator
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse save(TenantOperator tenantOperator) {
        //运营商组织代码只能是9位数字或字母
        if (tenantOperator.getTenantOperatorCode().trim().length() != 9 || (!isLetterDigit(tenantOperator.getTenantOperatorCode()))) {
            return TResponse.FAIL("分销商组织代码只能是9位数字或字母");
        }

        //自动转为大写
        tenantOperator.setTenantOperatorCode(tenantOperator.getTenantOperatorCode().toUpperCase());

        try {
            TenantOperator checkLoginNameExist = tenantOperatorService.checkLoginNameExist(tenantOperator.getLoginName());
            TenantUser checkLoginNameExist2 = tenantUserService.checkLoginNameExist(tenantOperator.getLoginName());
            if (checkLoginNameExist != null) {
                return TResponse.FAIL("此登录帐号已存在" + checkLoginNameExist.getLoginName());
            }
            if (checkLoginNameExist2 != null) {
                return TResponse.FAIL("此登录帐号已存在" + checkLoginNameExist2.getLoginName());
            }

            TenantOperator checkPhoneExist = tenantOperatorService.checkPhoneExist(tenantOperator.getPhone());
            TenantUser checkPhoneExist2 = tenantUserService.checkPhoneExist(tenantOperator.getPhone());
            if (checkPhoneExist != null || checkPhoneExist2 != null) {
                return TResponse.FAIL("此手机号已存在" + tenantOperator.getPhone());
            }

            TenantOperator operatorCodeExist = tenantOperatorService.checkOperatorCodeExist(tenantOperator.getTenantOperatorCode());
            TenantUser operatorCodeExist2 = tenantUserService.checkTenantCodeExist(tenantOperator.getTenantOperatorCode());
            if (operatorCodeExist != null || operatorCodeExist2 != null) {
                return TResponse.FAIL("此组织机构代码已存在" + tenantOperator.getTenantCode());
            }

            TenantUser user = ShiroUtils.getSessionUser();
            tenantOperatorService.insertOperatorAndUser(tenantOperator, user);
        } catch (Exception e) {
            logger.error("保存信息失败", e);
            return TResponse.FAIL("操作失败");
        }
        return TResponse.SUCCESS();
    }

    /**
     * 修改保存
     *
     * @param record
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public TResponse update(TenantOperator record) {
        try {
            tenantOperatorService.updateByPrimaryKeySelective(record);
        } catch (Exception e) {
            logger.error("保存信息失败", e);
            return TResponse.FAIL("操作失败");
        }
        return TResponse.SUCCESS();
    }

    /**
     * 修改状态
     *
     * @param loginName
     * @return
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateStatus(String loginName) {
        TenantOperator tenantOperator = tenantOperatorService.selectByLoginName(loginName);
        TenantUser tenantUser = tenantUserService.selectByLoginName(loginName);
        if (tenantOperator == null || tenantUser == null) {
            return TResponse.FAIL("登录帐号不存在" + loginName);
        }

        try {
            tenantOperatorService.updateOperatorAndUserStatus(tenantOperator, tenantUser);
        } catch (Exception e) {
            logger.error("更改状态失败", e);
            return TResponse.FAIL("操作失败");
        }
        return TResponse.SUCCESS();
    }

    /**
     * 设置密码
     *
     * @param loginName
     * @return
     */
    @RequestMapping(value = "/updateOperatorPassword", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateOperatorPassword(String loginName, String password, String verifyPassword) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getLoginName().equals(loginName)) {
            return TResponse.FAIL("不能重置自己密码");
        }

        TenantUser findUser = tenantUserService.selectByLoginName(loginName);
        if (findUser == null) {
            return TResponse.FAIL("未找到对应的账号,账号可能被修改");
        }

        if (StringUtils.isBlank(findUser.getMobile()) || !findUser.getMobile().matches(HttpConstant.MOBILE_REGEX)) {
            return TResponse.FAIL("手机号格式不正确" + findUser.getMobile());
        }

        TenantOperator tenantOperator = tenantOperatorService.selectByLoginName(loginName);
        TenantUser tenantUser = tenantUserService.selectByLoginName(loginName);
        if (tenantOperator == null || tenantUser == null) {
            return TResponse.FAIL("登录帐号不存在" + loginName);
        }

        if (!password.equals(verifyPassword)) {
            return TResponse.FAIL("两次输入的密码不一致");
        }

        try {
            tenantOperatorService.updateOperatorAndUserPassword(tenantOperator, tenantUser, password);
        } catch (Exception e) {
            return TResponse.FAIL("操作失败");
        }

        return TResponse.SUCCESS();
    }

    /**
     * 正则表达式判断字符串是否仅含有数字和字母
     *
     * @param str
     * @return
     */
    private static boolean isLetterDigit(String str) {
        String regex = "^[a-z0-9A-Z]+$";
        return str.matches(regex);
    }


    /**
     * 跳转桩群列表
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/operatorElecStation/{tenantOperatorCode}", method = RequestMethod.GET)
    public String operatorElecStation(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        return "/templates/operator/operatorElecStation";
    }

    /**
     * 获取分销商桩群列表数据
     *
     * @param baseSearch
     * @return
     */
    @RequestMapping(value = "/listPageOperatorElecStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageOperatorElecStation(BaseSearch baseSearch) {
        PageInfo<OperatorElecStationVo> pageInfo = tenantOperatorService.listPageOperatorElecStation(baseSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 更改申报方式
     *
     * @return
     */
    @RequestMapping(value = "/updatebatchType", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updatebatchType(@RequestParam(value = "operatorStationIdList") List<Long> operatorStationIdList
            , @RequestParam(value = "govtHlhtType") String govtHlhtType, @RequestParam(value = "tenantOperatorCode") String tenantOperatorCode) {
        try {
            tenantOperatorService.updatebatchType(operatorStationIdList, govtHlhtType,tenantOperatorCode);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更改申报方式失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 导出分销商列表
     */
    @ResponseBody
    @RequestMapping("/exportTenantOperator")
    public TResponse exportTenantOperator(OperatorSearch search, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");

        try {
            ExportUtils.setDefaultPaging(search);
            List<TenantOperator> list = tenantOperatorService.listExportTenantOperator(search);

            logger.info(search.getTenantCode() + ",tenantOperator/exportTenantOperator");

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分销商列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TenantOperator.class).sheet("分销商列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出分销商列表失败", e);
            return TResponse.FAIL("操作失败");
        }

    }
}
